<template>
  <div>
    <input type="text" v-model="state2.item.name" />
    <input type="text" v-model="state2.item.age" />
    <button @click="addItem">添加数据</button>
    <ul>
      <li
        @click="removeItem(index, state.list)"
        v-for="(item, index) in state.list"
        :key="index"
      >
        {{ item.name }}--{{ item.age }}
      </li>
    </ul>
    <Com :data="data.tableData"></Com>
  </div>
</template>
<script>
import { ref, reactive, watch, onMounted } from "vue";
import Com from "./Com.vue";
export default {
  setup() {
    // 渲染列表
    const { state, removeItem } = renderList();
    const { state2, addItem } = newState(state);
    const data = reactive({
      tableData: [],
    });
    // watch(
    //   () => state.list,
    //   (list) => {
    //     console.log(list);
    //   }
    // );
    onMounted(() => {
      setTimeout(() => {
        data.tableData = [1, 2, 5];
      }, 2000);
    });

    return {
      state,
      removeItem,
      addItem,
      state2,
      data,
    };
  },
  components: {
    Com,
  },
};
// 渲染列表的逻辑
function renderList() {
  const state = reactive({
    list: [
      {
        name: "GuanYu",
        age: "56",
      },
      {
        name: "ZhangFei",
        age: "54",
      },
      {
        name: "MaChao",
        age: "77",
      },
    ],
  });
  function removeItem(i) {
    state.list = state.list.filter((val, index) => i !== index);
  }
  return { state, removeItem };
}
// 添加的逻辑
function newState(state) {
  let state2 = ref({
    item: {
      name: "",
      age: "",
    },
  });
  function addItem() {
    console.log(state2);
    state.list.push(Object.assign({}, state2.value.item));
    state2.value.item.name = "";
    state2.value.item.age = "";
  }
  return {
    state2,
    addItem,
  };
}
</script>
<style scoped></style>
